<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="categoryData">
      <el-form-item label="类别名称" :label-width="formLabelWidth">
        <el-input v-model="categoryData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth">
        <el-input v-model="categoryData.sort" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  catgoryCreateOrUpdate,
  getAllResourceCategory
} from '@/api/resource-category'
export default {
  name: 'ResourceCategoryCreateOrUpdate',
  data () {
    return {
      isCreate: true,
      dialogFormVisible: false,
      categoryData: {
        id: undefined,
        name: '',
        sort: 0
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    title () {
      return this.isCreate ? '创建' : '编辑'
    }
  },
  methods: {
    showAndInit (id = 0) {
      this.dialogFormVisible = true
      this.isCreate = id < 1
      if (this.isCreate) {
        this.categoryData = { id: undefined, name: '', sort: 0 }
      } else {
        getAllResourceCategory().then((res) => {
          if (res.data.code === '000000') {
            const cate = res.data.data.find((item) => item.id === id)
            this.categoryData = cate
          }
        })
      }
    },
    onSubmit () {
      catgoryCreateOrUpdate(this.categoryData)
        .then((res) => {
          if (res.data.data) {
            this.$message.success(`${this.title}资源类别成功`)
            this.$emit('changeCategory')
          } else {
            this.$message.success(`${this.title}资源类别失败`)
          }
        })
        .finally(() => {
          this.dialogFormVisible = false
        })
    }
  }
}
</script>
<style scoped lang="scss">
</style>
